package com.test.springboot.alicloudoss.controller;

import com.alibaba.fastjson.JSON;
import com.aliyun.oss.model.OSSObjectSummary;
import com.test.springboot.alicloudoss.pojo.AlicloudOssPojo;
import com.test.springboot.alicloudoss.service.impl.AlicloudOssServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author thinkpad - 83start
 * @version v1.0
 * @create 2022/8/10 18:52
 * @package com.test.springboot.alicloudoss.controller
 * @description 阿里云OSS 控制类
 */

@RestController
@Slf4j
public class AlicloudOssController {

    @Autowired
    private AlicloudOssServiceImpl alicloudOssService;

    /**
     * 文件上传到oss
     * 参考url路径：
     * @param file
     * @param filePath
     * @return
     * @throws Exception
     */
    @PostMapping("upload/path")
    public String upload(@RequestParam("file") MultipartFile file,
                         @RequestParam(value = "filePath",defaultValue = " ") String filePath)
            throws Exception {
        AlicloudOssPojo alicloudOssPojo = this.alicloudOssService.upload(file,filePath);

        log.info("日志文件：" + JSON.toJSONString(alicloudOssPojo));

        // 判断是否传输成功，如果传输成功，则返回访问地址。
        if (alicloudOssPojo.getResponse().equals("success")){
            return alicloudOssPojo.getName();
        }else {
            return "传输失败，请检查后重试";
        }
    }

    /**
     * 根据文件名删除oss上的文件
     * @param fileName
     * @return
     * @throws Exception
     */
    @DeleteMapping("delete")
    public AlicloudOssPojo delete(@RequestParam("fileName") String fileName) throws Exception {
        return this.alicloudOssService.delete(fileName);
    }

    /**
     * 查询oss上的所有文件
     * @return
     * @throws Exception
     */
    @GetMapping("list")
    public List<OSSObjectSummary> list() throws Exception {
        List<OSSObjectSummary> OssList = this.alicloudOssService.list();
        log.info(JSON.toJSONString(OssList));
        return OssList;
    }

    /**
     * 根据文件名下载oss上的文件
     * @param fileName
     * @param response
     * @throws IOException
     */
    @PostMapping("download")
    public void download(@RequestParam("fileName") String fileName,
                         HttpServletResponse response) throws IOException {
        //通知浏览器以附件形式下载
        response.setHeader("Content-Disposition",
                "attachment;filename=" + new String(fileName.getBytes(), "ISO-8859-1"));
        this.alicloudOssService.exportOssFile(response.getOutputStream(),fileName);
    }
}
